﻿using System;
using System.Collections.Generic;
using Opalis.QuickIntegrationKit;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Collections;

namespace Active_Directory
{
    [OpalisObject("Delete AD User", ShowFilters = false)]
    class DeleteUser : IOpalisObject
    {
        private ConnectionCredentials credentials;

        [OpalisConfiguration]
        public ConnectionCredentials Credentials
        {
            get { return credentials; }
            set { credentials = value; }
        }

        public void Design(IOpalisDesigner designer)
        {
            designer.AddInput("User LDAP Path").WithDefaultValue("LDAP://CN=UserName,OU=Container,DC=Contoso,DC=Com");
            designer.AddOutput("Deleted User LDAP Path").AsString();
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            string deletedUserLDAPPath = request.Inputs["User LDAP Path"].AsString();
            string userName = deletedUserLDAPPath.Split(',')[0].Substring(10);
            string container = "LDAP://" + deletedUserLDAPPath.Substring(11 + userName.Length);

            DirectoryEntry dirEntry = new DirectoryEntry(container, credentials.UserName + "@" + credentials.Domain, credentials.Password);
            DirectoryEntry user = dirEntry.Children.Find("CN=" + userName, "user");

            dirEntry.Children.Remove(user);
            dirEntry.CommitChanges();
            dirEntry.Close();

            response.Publish("Deleted User LDAP Path", deletedUserLDAPPath);
        }
    }
}
